#include<iostream>
#include<sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <strings.h>
#include "log.hpp"
#define SIZE 1024

void Usage(std::string proc)
{
    std::cout << "\nUsage: "<< proc << " port ip\n" << std::endl;
}


//启动客户端：./udpclient 127.0.0.1 8080
int main(int argc, char* argv[])
{
    //判断命令行参数是否正确
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    //创建套接字
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
        logMessage(ERROR,"client| create socket failed.");
        exit(2);
    }
    logMessage(DEBUG,"client| create socket succeed.");

    //无需绑定，直接发送消息，并接收消息
    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));
    socklen_t len = sizeof(server_addr);
    while(true)
    {
        //发送消息
        std::cout << "client-请输入# "; 
        std::string message;
        std::getline(std::cin,message);
        if(message == "quit")
            break;
        sendto(sock,message.c_str(),message.size(),0,(struct sockaddr*)&server_addr,len);

        //接收消息
        char client_buffer[SIZE];
        struct sockaddr_in temp;
        bzero(&temp,sizeof temp);
        socklen_t temp_len=sizeof(temp);
        ssize_t n = recvfrom(sock,client_buffer,sizeof client_buffer, 0,(struct sockaddr*)&temp,&temp_len);
        if(n > 0)
        {
            client_buffer[n] = 0;
            std::cout << "server echo : " << client_buffer << std::endl;
        }
        
    }
    close(sock);

    return 0;
}